<?php

final class Response {
    use \Lib\Traits\StaticClass;

    /**
     * 返回数据
     *
     * @param string|array|\Base\Model\AbstractModel $data
     * @param string                                 $msg
     * @param int                                    $code
     *
     * @return false
     */
    public static function data($data, $msg = null, $code = 200) {

        $resource         = ['status' => true, 'code' => (int)$code];
        $resource['msg']  = $msg;
        $resource['data'] = is_array($data)
            ? $data
            : ($data instanceof \Base\Model\AbstractModel ? $data->toArray() : (string)$data);

        header('Content-type: application/json; charset=utf-8');
        echo \json_encode($resource);

        return false;
    }

    /**
     * Error
     *
     * @param string $msg
     * @param int    $code
     *
     * @return false
     */
    public static function error($msg = null, $code = 0) {
        $resource = [
            'status' => false,
            'code'   => (int)$code,
            'msg'    => (string)$msg,
        ];

        header('Content-type: application/json; charset=utf-8');
        echo \json_encode($resource);

        return false;
    }

    /**
     * 回调
     *
     * @param array|string $msg
     * @param string       $callback
     * @return boolean
     */
    public static function callback($msg, $callback) {
        if(!!$callback && preg_match('/^[a-zA-Z_][a-zA-Z0-9_\.]*$/', (string)$callback)) {
            $msg = is_array($msg) ? $msg : [$msg];

            header('Content-type: application/javascript; charset=utf-8');
            echo $callback . '(' . \json_encode($msg) . ');';

            return true;
        }

        return self::error('invalid callable');
    }

    /**
     * @desc 成功返回信息并跳转
     *
     * @param string $msg
     * @param string $url
     * @return bool
     */
    public static function msg($msg = '编辑成功', $url = '') {
        if(empty($url)) {
            $request              = \Yaf\Dispatcher::getInstance()->getRequest();
            $prefix['module']     = strtolower($request->getModuleName());
            $prefix['controller'] = strtolower($request->getControllerName());
            $prefix['action']     = 'list';
            $url                  = '/' . trim(implode('/', $prefix), '/');
        }

        $resource = ['status' => true, 'msg' => $msg, 'url' => $url];
        echo \json_encode($resource);
        return false;
    }

    /**
     * @desc 失败返回信息
     *
     * @param string $msg
     * @return bool
     */
    public static function errmsg($msg = '编辑失败') {
        $resource = ['status' => false, 'msg' => $msg];
        echo \json_encode($resource);
        return false;
    }
}
